package com.mo.modular.system.service.impl;

import java.io.IOException;

import org.springframework.web.multipart.MultipartFile;

import com.mo.modular.system.service.IFastDFSService;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.Charset;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.exception.FdfsUnsupportStorePathException;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.mo.config.properties.FastDFSProperties;
import com.mo.config.properties.NginxProperties;

@Service
public class FastDFSServiceImpl implements IFastDFSService{

	@Autowired
    private FastFileStorageClient storageClient;
	
	@Autowired
    private NginxProperties nginxProperties;
	

	@Override
	public String uploadFile(MultipartFile file) throws IOException {
		StorePath storePath = storageClient.uploadFile(file.getInputStream(),file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()),null);
        return getResAccessUrl(storePath);
	}

	@Override
	public String uploadFile(String content, String fileExtension) {
		byte[] buff = content.getBytes(Charset.forName("UTF-8"));
        ByteArrayInputStream stream = new ByteArrayInputStream(buff);
        StorePath storePath = storageClient.uploadFile(stream,buff.length, fileExtension,null);
        return getResAccessUrl(storePath);
	}

	@Override
	public void deleteFile(String fileUrl) {
		 if (StringUtils.isEmpty(fileUrl)) {
	            return;
	     }
        try {
            StorePath storePath = StorePath.praseFromUrl(fileUrl);
            storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
        } catch (FdfsUnsupportStorePathException e) {
            e.printStackTrace();
        }
		
	}
	
	// 封装图片完整URL地址
    private String getResAccessUrl(StorePath storePath) {
        //String fileUrl = AppConstants.HTTP_PRODOCOL + appConfig.getResHost()
         //       + ":" + appConfig.getFdfsStoragePort() + "/" + storePath.getFullPath();

    	//String fileUrl = nginxProperties.getHostUrl()+storePath.getFullPath();
        return storePath.getFullPath();
    }

}
